package vip.liux.front.domain.models.chat;

import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.Table;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.springframework.util.Assert;
import vip.liux.front.domain.enums.ChatMessageSide;

import java.time.Instant;

/**
 * 聊天会话
 */
@EqualsAndHashCode(callSuper = true)
@Data
@Entity
@Table(name = "chat_conversations")
@org.springframework.data.relational.core.mapping.Table("chat_conversations")
public class ChatConversation extends vip.liux.domain.entities.Entity<Long> {

    /**
     * 租户ID
     */
    @Column(name = "tenant_id")
    private String tenantId;

    /**
     * 用户ID
     */
    @NotNull
    @Column(name = "user_id", nullable = false)
    private Long userId;

    /**
     * 目标用户ID
     */
    @NotNull
    @Column(name = "target_user_id", nullable = false)
    private Long targetUserId;

    /**
     * 最后一条消息的发送方/接收方
     * @see ChatMessageSide
     */
    @Column(name = "last_message_side")
    private Integer lastMessageSide;

    /**
     * 最后一条消息
     */
    @Size(max = 4096)
    @Column(name = "last_message", length = 4096)
    private String lastMessage;

    /**
     * 最后一条消息时间
     */
    @NotNull
    @Column(name = "last_message_date", nullable = false)
    private Instant lastMessageDate;

    /**
     * 未读消息数量
     */
    @NotNull
    @Column(name = "unread_message_count", nullable = false)
    private int unreadMessageCount;

    public ChatConversation() {
    }

    public ChatConversation(Long userId, Long targetUserId, String tenantId) {
        this.userId = userId;
        this.targetUserId = targetUserId;
        this.tenantId = tenantId;
    }

    // 添加未读消息数量
    public void addUnreadMessage() {
        addUnreadMessage(1);
    }

    // 添加未读消息数量
    public void addUnreadMessage(int count) {
        unreadMessageCount += count;
    }

    // 重置未读消息数量
    public void resetUnreadMessageCount() {
        unreadMessageCount = 0;
    }

    public void setLastMessage(String messageText, Instant messageTime, ChatMessageSide side) {
        Assert.notNull(messageText, "messageText cannot be null");

        lastMessage = messageText;
        lastMessageDate = messageTime;
        lastMessageSide = side.ordinal();

        if (side == ChatMessageSide.Receiver) {
            addUnreadMessage();
        } else {
            resetUnreadMessageCount();
        }
    }
}